package edu.gatech.wms.views;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import edu.gatech.wms.R;
import edu.gatech.wms.controllers.ItemManager;
import edu.gatech.wms.controllers.Login;
import edu.gatech.wms.models.DonatedItem;
import edu.gatech.wms.models.FoundItem;
import edu.gatech.wms.models.ItemType;
import edu.gatech.wms.models.LostItem;

public class CreateItemActivity extends Activity {
	private int				key;
	private EditText		itemName, location, description;
	//private LocationManager	service;
	//private LocationListener	locationSeeker;
	private Address			itemAddress;
	//private Location systemLocation;
	private ImageButton itemPic;
	private Bitmap bitmap;
	
	private static final int REQUEST_CODE = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.create_item);
		
		SharedPreferences preferences = PreferenceManager
				.getDefaultSharedPreferences(this);
		key = preferences.getInt(Login.ACTIVE_KEY, 0);
		
		itemName = (EditText) findViewById(R.id.create_item_name);
		location = (EditText) findViewById(R.id.create_item_location);
		description = (EditText) findViewById(R.id.create_item_description);
		itemPic = (ImageButton) findViewById(R.id.create_item_upload_image);
			
		itemPic.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v) 
			{
				Intent intent = new Intent();
				intent.setType("image/*");
				intent.setAction(Intent.ACTION_GET_CONTENT);
				intent.addCategory(Intent.CATEGORY_OPENABLE);
				startActivityForResult(intent, REQUEST_CODE);
			}
		});
		
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(itemName.getWindowToken(), 0);
		imm.hideSoftInputFromWindow(location.getWindowToken(), 0);
		imm.hideSoftInputFromWindow(description.getWindowToken(), 0);
		
		// LOCATION StuFF BEGINS
		//service = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		
		// Check if enabled and if not send user to the GSP settings
		// Better solution would be to display a dialog and suggesting to
		// go to the settings
		/*if ( !service.isProviderEnabled(LocationManager.GPS_PROVIDER) ) {
			Toast.makeText(getBaseContext(), "EEK! GPS NOT ENABLED!",
					Toast.LENGTH_SHORT).show();
			Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
			startActivity(intent);
		} else {
		
		locationSeeker = new LocationListener() {
			
			public void onLocationChanged(Location location) {
				systemLocation = location;
			}
			
			public void onProviderDisabled(String provider) {
				
			}
			
			public void onProviderEnabled(String provider) {
				
			}
			
			public void onStatusChanged(String provider, int status,
					Bundle extras) {
				
			}
		};*/
		
		//final int MINIMUM_TIME_BETWEEN_UPDATES = 1;
		//final int MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1000;
		/*service.requestLocationUpdates(LocationManager.GPS_PROVIDER,
				MINIMUM_TIME_BETWEEN_UPDATES,
				MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, locationSeeker);
		
		 */		
		
		//Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault());
		/*
		try {
			List<Address> addresses = new ArrayList<Address>();
			int tries = 0;
			do {
				systemLocation = service.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
				if ( systemLocation != null) {
					addresses = geocoder.getFromLocation(systemLocation.getLatitude(), systemLocation.getLongitude(), 1);
				}
				tries++;
			} while ( addresses.size() == 0 && tries < 5 );
			if ( addresses.size() > 0 ) {
				location.setText(addresses.get(0).getAddressLine(0));
				itemAddress = addresses.get(0);
			}
		} catch (IOException e) {
			Toast.makeText(getParent(),
					"Problem with from LOCATION from GPS!!", Toast.LENGTH_SHORT)
					.show();
		}*/
		//}
		
		findViewById(R.id.create_item_submit).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						View focusView = null;
						boolean cancel = true;
						
						RadioGroup radioGroup = (RadioGroup) findViewById(R.id.create_item_radioGroup);
						int radioGroupId = radioGroup.getCheckedRadioButtonId();
						
						ItemType itemType = null;
						switch ( radioGroupId ) {
							case R.id.create_item_radioBtn_lost:
								itemType = new LostItem();
								break;
							case R.id.create_item_radioBtn_found:
								itemType = new FoundItem();
								break;
							case R.id.create_item_radioBtn_donation:
								itemType = new DonatedItem();
								break;
						}
						
						String _itemName = itemName.getText().toString();
						String _location = location.getText().toString();
						String _description = description.getText().toString();
						List<String> categories = new ArrayList<String>();
						
						CheckBox c1 = (CheckBox) findViewById(R.id.create_item_checkBox_1);
						CheckBox c2 = (CheckBox) findViewById(R.id.create_item_checkBox_2);
						CheckBox c3 = (CheckBox) findViewById(R.id.create_item_checkBox_3);
						CheckBox c4 = (CheckBox) findViewById(R.id.create_item_checkBox_4);
						CheckBox c5 = (CheckBox) findViewById(R.id.create_item_checkBox_5);
						CheckBox c6 = (CheckBox) findViewById(R.id.create_item_checkBox_6);
						
						if ( c1.isChecked() ) {
							categories.add(c1.getText().toString());
						}
						
						if ( c2.isChecked() ) {
							categories.add(c2.getText().toString());
						}
						
						if ( c3.isChecked() ) {
							categories.add(c3.getText().toString());
						}
						
						if ( c4.isChecked() ) {
							categories.add(c4.getText().toString());
						}
						
						if ( c5.isChecked() ) {
							categories.add(c5.getText().toString());
						}
						
						if ( c6.isChecked() ) {
							categories.add(c6.getText().toString());
						}
						
						if ( TextUtils.isEmpty(_itemName) ) {
							itemName.setError(getString(R.string.error_field_required));
							focusView = itemName;
							cancel = false;
						}
						
						if ( !TextUtils.isEmpty(_location) && (itemAddress != null && !_location.equals(itemAddress.getAddressLine(0)))) {
							Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault());
								try {
									List<Address> results;
									int timeout = 0;
									do {
										results = geocoder.getFromLocationName(_location, 1);
										timeout++;
									}	while ( results.size() == 0 && timeout < 100);
									if (results.size() > 0) {
										itemAddress = results.get(0);
									}
								} catch (IndexOutOfBoundsException e) {
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
						} 
						
						if ( categories.isEmpty() ) {
							Toast.makeText(getBaseContext(),
									"Please select at least one category",
									Toast.LENGTH_LONG).show();
							cancel = false;
						}
						
						if ( cancel ) {
							ItemManager.createItem(_itemName, itemType, _description, bitmap, key, itemAddress, categories);
							//service.removeUpdates(locationSeeker);
							finish();
						} else {
							focusView.requestFocus();
						}
						
					}
				});
		
		findViewById(R.id.create_item_cancel).setOnClickListener(
				new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						finish();
					}
				});
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) 
	{
		if(REQUEST_CODE == requestCode && resultCode == Activity.RESULT_OK)
		{
			try
			{
				if(bitmap != null)
					bitmap.recycle();
				InputStream inStream = getContentResolver().openInputStream(data.getData());
				bitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeStream(inStream), itemPic.getWidth(), itemPic.getHeight(), true);
				inStream.close();
				itemPic.setImageBitmap(bitmap);
			}
			catch(FileNotFoundException e)
			{
				e.printStackTrace();
			}
			catch(IOException e)
			{
				e.printStackTrace();
			}
		}
		
		super.onActivityResult(requestCode, resultCode, data);
	}
}